/* 冻结解冻记录
 * @Author: Setsuna
 * @Email: 601890383@qq.com
 * @FilePath: \src\pages\QuotaManage\QuotaAdjust\FreezeRecord.tsx
 * @Date: 2021-09-02 10:20:30
 * @LastEditTime: 2021-09-06 12:04:21
 */
import React from 'react'
import { UdTable, UdFilter, columnRenders, http, UdToolbar, UdDrawer } from '@/lib'
import { Select, Spin, Button, Input, TreeSelect, Tag, message, Tooltip } from 'antd'
import quotaApis from '@/apis/AboutQuota'
import comApis from '@/apis'
import UdSelect from '@/components/UdFormControls/UdSelect'
import FreezeDetails from './component/FreezeDetails'
import AboutQuota from '@/apis/AboutQuota'
import apis from '@/apis'
import { downBlobFile, downBlobFileXlsx } from '@/utils/methods'
import { WrappedFormUtils } from 'antd/lib/form/Form'
import _ from 'lodash'
const { TreeNode } = TreeSelect
const { Option } = Select

export default class FreezeRecord extends React.Component<IProps, IState> {
  protected filterForm: WrappedFormUtils = {} as WrappedFormUtils
  private brandList: any[] = this.props.brandList //品牌公司
  private STATUS_ENUM: any = {
    AUDITING: '审核中',
    AUDITFAIL: '已拒绝',
    AUDITSUCC: '已通过',
  }
  private FROZEN_STATUS_ENUM: any = {
    0: '解冻',
    1: '冻结',
  }
  private PLAN_TYPE_ENUM: any = {
    0: '计划内',
    1: '计划外',
  }
  private conditions: any = [
    {
      label: '品牌公司',
      id: 'brandCode',
      initialValue: this.brandList[0].value,
      render: (
        <UdSelect
          showSearch
          allowClear={false}
          options={this.brandList}
          onChange={value => {
            this.changeBrandCode(value)
          }}
        />
      ),
    },
    {
      label: '配额品项',
      id: 'prodBarcode',
      render: () => (
        <UdSelect
          showSearch
          options={this.state.prodBarCodeList}
          onChange={value => this.getManageImportStageName({ prodBarcode: value })}
        />
      ),
    },
    {
      label: '片区名称',
      id: 'belongAreaName',
      render: () => (
        <TreeSelect showSearch treeNodeFilterProp="title">
          {this.mapTree(this.state.treeDataList)}
        </TreeSelect>
      ),
    },
    {
      label: '考核年度',
      id: 'stageYear',
      render: () => (
        <UdSelect
          options={this.state.stageYearList}
          showSearch={true}
          optionFilterProp="children"
          onChange={value => this.getManageImportStageName({ stageYear: value })}
        />
      ),
    },
    {
      label: '考核阶段',
      id: 'stageName',
      render: () => <UdSelect options={this.state.stageNameList} showSearch={true} />,
    },
    {
      label: '客户名称',
      id: 'dealerName',
      render: () => <Input />,
    },
    {
      label: '客户编码',
      id: 'dealerCode',
      render: () => <Input />,
    },
    {
      label: '申请类型',
      id: 'frozenStatus',
      render: (
        <Select>
          <Option value="0">解冻</Option>
          <Option value="1">冻结</Option>
        </Select>
      ),
    },
    {
      label: '计划类型',
      id: 'planType',
      render: () => (
        <Select>
          <Option value={1}>计划外</Option>
          <Option value={0}>计划内</Option>
        </Select>
      ),
    },
    {
      id: 'approvalStatus',
      label: '审批状态',
      render: () => (
        <Select>
          <Option value="AUDITING">审核中</Option>
          <Option value="AUDITFAIL">已拒绝</Option>
          <Option value="AUDITSUCC">已通过</Option>
        </Select>
      ),
    },
  ]
  private columns: any = [
    ['序号', 'id', (text, record, index) => index + 1, { width: '50px' }],
    { title: '客户编码', dataIndex: 'dealerCode', minWidth: '120px' },
    { title: '客户名称', dataIndex: 'dealerName', minWidth: '120px' },
    { title: '品牌公司', dataIndex: 'brandName', minWidth: '120px' },
    { title: '配额品项', dataIndex: 'prodBarname', minWidth: '120px' },
    {
      title: '同步状态',
      key: 'isOrder',
      dataIndex: 'isOrder',
      render: (text, record) => {
        let obj = {
          1: '失败',
          0: '成功',
        }
        let state = obj[record.isOrder]
        //* 23-10-7 审核中不显示同步状态
        return (record.isOrder != null&&record.approvalStatus!=='AUDITING') ?<Tag color={text === 0 ? '#87d068' : '#f50'}>{state}</Tag>:''
      },
      width: '100px',
    },
    { title: '所属片区', dataIndex: 'belongAreaName', minWidth: '120px' },
    {
      title: '计划类型',
      dataIndex: 'planType',
      minWidth: '80px',
      render: (text, record) => {
        return this.PLAN_TYPE_ENUM[record.planType] || ''
      },
    },
    {
      title: '申请类型',
      dataIndex: 'frozenStatus',
      minWidth: '60px',
      render: (text, record) => {
        return this.FROZEN_STATUS_ENUM[record.frozenStatus] || ''
      },
    },
    { title: '考核年度', dataIndex: 'stageYear', minWidth: '60px' },
    {
      title: '考核阶段',
      dataIndex: 'stageName',
      width: 150,
      render: (text, record) => {
        return (
          <Tooltip title={record.stageName}>
            <div style={{ width: '150px', overflow: 'hidden', whiteSpace: 'nowrap', textOverflow: 'ellipsis' }}>
              {record.stageName}
            </div>
          </Tooltip>
        )
      },
    },
    {
      title: '配额有效期',
      dataIndex: 'term',
      minWidth: '160px',
      render: (text, record) => {
        return `${record.stageBeginTime}-${record.stageEndTime}`
      },
    },
    {
      title: '审核状态',
      dataIndex: 'approvalStatus',
      minWidth: '120px',
      render: (text, record) => {
        return this.STATUS_ENUM[record.approvalStatus] || ''
      },
    },
    { title: '操作人', dataIndex: 'createName', minWidth: '100px' },
    { title: '操作时间', dataIndex: 'createTime', minWidth: '120px' },
    {
      title: '操作',
      dataIndex: 'operate',
      fixedWidth: '70px',
      fixed: 'right',
      render: columnRenders.operate([
        { title: '查看', action: (text, record) => this.handleDetails(record) },
        {
          title: '重发',
          show: (text: any, record: any) => record['isOrder'] === 1 && record['approvalStatus'] === 'AUDITSUCC',
          action: (text: any, record: any) => this.handQuotaRetry(record),
        },
      ]),
    },
  ]
  private tableProps: any = { rowKey: 'id', scroll: { x: true } }

  constructor(props) {
    super(props)
    this.state = {
      dataSource: [],
      searchValues: {
        brandCode:this.brandList[0].value,
      },
      page: 1,
      size: 10,
      total: 0,
      loading: false,
      uploading: false,
      downloading: false,
      stageYearList: [],
      prodBarCodeList: [],
      treeDataList: [],
      stageNameList: [], //考核阶段
    }
  }

  render() {
    return (
      <Spin
        spinning={this.state.uploading || this.state.downloading}
        tip={this.state.uploading ? '上传中，请稍后...' : '下载中，请稍后...'}
      >
        <UdFilter
          getForm={form => {
            this.filterForm = form
          }}
          items={this.conditions}
          onSearch={values => {
            this.handleSearch(values)
          }}
          loading={this.state.loading}
          resetAfter={this.resetFilterHandle}
        />
        <UdToolbar
          other={
            <Button type="primary" onClick={this.downloadDetailFrozenExcel}>
              导出
            </Button>
          }
        ></UdToolbar>
        <UdTable
          columns={this.columns}
          dataSource={this.state.dataSource}
          onChange={this.handleChangePage}
          {...this.tableProps}
          pagination={{
            current: this.state.page,
            pageSize: this.state.size,
            total: this.state.total,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['10', '20', '30', '40'],
            showTotal: (total, range) => `共${total}项，当前${range[0]}-${range[1]}项`,
          }}
        ></UdTable>
      </Spin>
    )
  }

  private handQuotaRetry = (record: { tradeCode: string }) => {
    http.post(quotaApis.quotaRetry, { tradeCode: record.tradeCode, type: 1 }).then(res => {
      message.success('操作成功')
      this.handleSearch(this.filterForm.getFieldsValue())
    })
  }

  //获取考核阶段
  private getManageImportStageName = (params?: any) => {
    this.setState({ stageNameList: [] }, () => {
      this.filterForm.setFieldsValue({ stageName: undefined })
    })

    let searchValues = this.filterForm.getFieldsValue()
    searchValues = { ...searchValues, ...params }
    if (searchValues.stageYear == null && searchValues.brandCode == null && searchValues.prodBarcode == null) {
      return false
    }
    http
      .get(quotaApis.getManageImportStageName, {
        params: {
          stageYear: searchValues.stageYear,
          brandCode: searchValues.brandCode,
          prodBarcode: searchValues.prodBarcode,
        },
      })
      .then(res => {
        const stageNameList = _.uniqBy(
          res.data?.map(item => ({ value: item.stageName, title: item.stageName })) || [],
          'value'
        )
        this.setState({ stageNameList })
      })
  }

  //处理树数据
  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }

  //导出冻结解冻记录列表
  private downloadDetailFrozenExcel = () => {
    this.setState({ downloading: true })
    let {searchValues} = this.state
    let { brandCode } = searchValues
    let brandName = this.brandList.find(item => {
      return item.value === brandCode
    })?.title
    http
      .post(
        AboutQuota.downloadDetailFrozenExcel,
        {
          ...searchValues,
        },
        { responseType: 'arraybuffer' }
      )
      .then(res => {
        if (!res.data.code) {
          downBlobFileXlsx(res.data, `${brandName}-冻结解冻记录`)
        }
      })
      .finally(() => {
        this.setState({ downloading: false })
      })
  }

  // 品牌公司change事件
  private changeBrandCode = (value: any) => {
    this.setState({ prodBarCodeList: [], treeDataList: [], stageNameList: [] }, () => {
      this.filterForm.setFieldsValue({ prodBarcode: undefined, stageName: undefined, belongAreaName: undefined })
    })
    Promise.all([this.getProdBarList(value), this.getAreaList(value)]).then(res => {
      this.setState(
        {
          prodBarCodeList: res[0],
          treeDataList: res[1],
        },
        () => {
          this.getManageImportStageName({ brandCode: value })
        }
      )
    })
  }

  //获取配额品项
  private getProdBarList = (value: any) => {
    return http
      .get(quotaApis.getProdBarList, {
        params: { brandCode: value },
      })
      .then(res => {
        const { data = [] } = res
        const prodBarCodeList = data.map(item => ({ value: item.code, title: item.name }))
        return prodBarCodeList
      })
  }

  //获取片区
  private getAreaList = (value: any) => {
    return http
      .get(apis.getTreeByUser, {
        params: { organizationCode: value },
      })
      .then(res => {
        let data = res?.data?.children || []
        return data
      })
  }

  //获取考核年度
  private getStageYearList = () => {
    http.get(comApis.GetQuotaAssessYearList).then(res => {
      const stageYearList = res.data?.map(({ year: value, name: title }) => ({ value: value + '', title })) || []
      this.setState({ stageYearList })
    })
  }

  public componentDidMount() {
    this.getFreezeRecordTableData()
    this.getStageYearList()
    this.changeBrandCode(this.brandList[0].value)
  }

  public handleDetails = (record: any) => {
    UdDrawer.open({
      title: '审批详情',
      width: '50%',
      content: <FreezeDetails record={record} />,
      footer: null,
    })
  }

  private handleChangePage = pagination => {
    const { current: page, pageSize: size } = pagination
    this.setState({ page, size }, () => {
      this.getFreezeRecordTableData()
    })
  }
  private handleSearch = (values: any) => {
    this.setState({ searchValues: values, page: 1 }, () => {
      this.getFreezeRecordTableData()
    })
  }

  private resetFilterHandle = (form: WrappedFormUtils) => {
    this.setState({ dataSource: [], page: 1, total: 0, searchValues: form.getFieldsValue() }, () => {
      this.changeBrandCode(this.brandList[0].value)
      this.getFreezeRecordTableData()
    })
  }

  private getFreezeRecordTableData = async () => {
    this.setState({ loading: true })
    try {
      let list: any = await http.post(quotaApis.getDetailFrozenPage, {
        page: this.state.page,
        size: this.state.size,
        conditions: { brandCode: this.brandList[0].value, ...this.state.searchValues },
      })
      const dataSource = list.data?.content

      this.setState({
        dataSource,
        page: list.data.number,
        size: list.data.size,
        total: list.data.totalElements,
        loading: false,
      })
    } catch (error) {
      this.setState({
        loading: false,
      })
    }
  }
}

interface IProps {
  brandList: any[]
}
interface IState {
  dataSource?: any[]
  searchValues?: Record<string,any>
  page?: any
  size?: any
  total?: any
  loading?: boolean
  uploading?: boolean
  downloading?: boolean
  stageYearList: any[]
  prodBarCodeList: any[]
  treeDataList: any[]
  stageNameList: any[]
}
